<!--
 * @description  : 证件-实地核查信息录入页面
 * @descriptionDetail: 证件-实地核查信息录入页面
 * @copyright    : 浙江烟草
 * @author       : dw
 * @create       : 2022-11-15 15:29:13
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="true" backText="返回" title="许可核查"></theme-navbar>
    <!-- #endif -->

    <view class="content" style="height: 100%;">
      <!-- 申请信息（点击展开查看） -->
      <view>
        <u-collapse :head-style="applyHeadStyle" ref="applyCt">
          <u-collapse-item :disabled="from == 1" title="申请信息（点击展开查看）" :open="true">
            <u-form :label-width="labelWidth">
              <u-form-item label="申请类型">
                <view class="zk-disabled">
                  {{ fieldData.applyTypeName }}
                </view>
              </u-form-item>
              <u-form-item label="许可证号" v-if="fieldData.licNo">
                <view class="zk-disabled">
                  {{ fieldData.licNo }}
                </view>
              </u-form-item>
              <u-form-item label="联系人及电话">
                <view class="zk-disabled">
                  {{ fieldData.contactName }}   {{ fieldData.contactTel }}
                </view>
              </u-form-item>
              <u-form-item label="文书送达">
                <view class="zk-disabled">
                  {{ fieldData.sendTypeName }}
                </view>
              </u-form-item>
              <view v-if="pdfFiles.length!=0">
                <view v-for="(item, index) in pdfFiles" :key="index">
                  <u-form-item :label="item.docName" right-icon="/static/certificate/pdf.png" label-width="600" v-if="item.pdfFileId">
                    <view v-if="signViewUrl && from == 1 && SIGN_DOCS.includes(item.docCode)">
                      <u-icon v-if="docSign[item.docInsUuid]" name="share" :color="$theme.u_type_primary" size="28" @click="handleSign(item.docInsUuid)"></u-icon>
                      <u-icon v-else name="share" :color="$theme.u_type_success" size="28"></u-icon>
                    </view>
                    <u-image src="/static/certificate/pdf.png" mode="widthFix" width="28px" height="28px" slot="right" @click="downloadFile(item.pdfFileId)"></u-image>
                  </u-form-item>
                </view>
              </view>
            </u-form>
          </u-collapse-item>
        </u-collapse>
      </view>
      <!-- 实地核查确认信息 -->
      <view class="confirm-box" v-if="from == 0">
        <confirm-info-item
          :isElectronicCigarette="isElectronicCigarette"
          :docUpdateStatus="docUpdateStatus"
          :isLicDecide="isLicDecide"
          :preStep="step"
          :fieldData="docData"
          :docIns="docIns"
          ref="confirmForm"
          @ok="getVillages"
          @showVal="showDefalutVal"
          @getStreet="getStreetsData"
          @newStreet="getStreetsData"
        ></confirm-info-item>
      </view>
      <view class="gap-space" v-if="from == 0"></view>
      <!-- 底部按钮 -->
      <view class="submit-btns btn-other-cls" style="margin-left:-20rpx" v-if="from == 0">
        <u-button class="u-btn" type="error" v-if="['assigntaskCheck', 'assigntask'].includes(step)" @click="submitAudit('back')">
          退回
        </u-button>
        <u-button class="u-btn" type="error" v-if="step == 'sitecheck' " @click="submitAudit('back')">
          退回
        </u-button>
        <u-button class="u-btn" plain type="primary" v-if="step == 'sitecheck' " @click="saveAudit('save')">
          保存
        </u-button>
        <u-button class="u-btn" type="primary" v-if="step == 'sitecheck' " @click="saveAudit('submit')">
          提交
        </u-button>
        <u-button class="u-btn" type="primary" v-if="['assigntaskCheck', 'assigntask'].includes(step)" @click="submitAudit('submit')">
          提交
        </u-button>
      </view>
    </view>
    <u-popup v-model="qrcodeShow" mode="bottom" height="70%" @close="qrcodeShow=false">
      <view class="qrcodeContainer">
        <img :src="qrcodeImg" alt="暂无图片" />
        <p>请扫码签名</p>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {dateUtils,} from "@/common/util";
import certificateService from "@/service/certificate/certificate.service.js";
import confirmInfoItem from "./confirmInfoItem.vue";
import commonService from "@/service/common/common.service.js";
import {LOG_STATUS,LOG_OP_TYPE,} from '@/service/common/mapping/enum.js';
import {M_APPLY_TYPE_CODE,} from '@/service/certificate/mapping/enum.js';
import QRCode from 'qrcode';
export default {
  components: {
    confirmInfoItem,
  },
  data() {
    return {
      // 可以签名的文书：实地核查表、受理单、申请表、送达回证  , 'lic-doc-01-01-02', 'lic-doc-01-01-01', 'service-doc'
      SIGN_DOCS: ['lic-item-02-01-01',],
      beginTime:"",
      rightIconStyle: {
        'fontSize': '40rpx',
        'color': this.$theme.u_type_primary,
      },
      applyHeadStyle:{
        backgroundImage:"url('static/certificate/bh.png')",
        backgroundSize: '5% 50%',
        backgroundRepeat: 'no-repeat',
        paddingLeft: '26px',
        backgroundPosition:'left',
      },
      labelPosition:"top",
      labelWidth:'280',
      preParams:{},
      fieldData:{}, // 实地核查申请信息
      docIns:{},// 文书实例信息
      docData:{},
      pdfFiles:[], // 流程PDF文件
      areaDatas:[],// 行政区划数据
      streetData:[],// 街道数据
      villagesData:[],// 社区数据
      fileUrl:'',// pdf预览路径
      IMPORT_LIC_DATA:[],
      // isDisable:false,
      step:"",
      auditorList:[],
      applyType:"",  // 申请类型
      screenshot:'', // 周围零售户中小学截图
      docUpdateStatus:"",
      isLicDecide : "", //
      from : 0,
      qrcodeShow: false,
      qrcodeImg: null,
      isSigned: false,
      docSign: {},
      signViewUrl: null,
      isElectronicCigarette:false, // 是否是电子烟
    };
  },
  onLoad(opt) {
    this.from = opt.from;
    this.preParams = this.getRouteParam();
    commonService.getCurrentTime().then(res2 => {
      this.beginTime = res2.success ? res2.msg : this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss');
    });
    // 查询配置的第三方签名地址
    commonService.getThirdSign().then(ud => {
      if (ud.success) {
        this.signViewUrl = ud.data?.filter(d => d.configSubKey === 'viewUrl')[0]?.configValue;
      }
    });
  },
  onShow() {
    // 返回场景回显承载信息 经纬度&网格
    const backCache = this.$storage.get('backCache');
    if (backCache && this.$refs.confirmForm) {
      const { addrImg, position, gridInfo } = backCache;
      this.$refs.confirmForm.addrImgs.push(addrImg);
      this.$set(this.$refs.confirmForm.confirmInfo, 'gisXY', '经度：' + position[0] + ", 纬度：" + position[1]);
      this.$set(this.$refs.confirmForm.confirmInfo, 'longitude', position[0]);
      this.$set(this.$refs.confirmForm.confirmInfo, 'latitude', position[1]);
      this.$set(this.$refs.confirmForm.confirmInfo, 'gridUuid', gridInfo.gridUuid);
      this.$set(this.$refs.confirmForm.confirmInfo, 'gridName', gridInfo.gridName);
      this.$set(this.$refs.confirmForm.confirmInfo, 'gridCode', gridInfo.gridCode);
      this.$storage.remove('backCache');
    }
  },
  created(){
    commonService.bscCodesMap('L_LICENSING_MATTERS').then(res => {
      if (res.success) {
        this.IMPORT_LIC_DATA = res.bean['L_LICENSING_MATTERS'];
      }
    });
  },
  mounted() {
    // 初始化页面数据
    this.initDocData();
  },
  methods: {
    initDocData(){
      this.$u.loading("文书加载中...");
      certificateService.getDocIns(this.preParams.docInsUuid).then((docIns) => {
        this.$u.hideLoading();
        this.docIns = docIns.bean;
        this.step = docIns.bean.step;
        if(this.from == 0){
          // 文书信息
          this.initDoc();
        }else{
          this.initDoc2();
        }
        // 文书实例（pdf）文件
        this.searchApplyPdf();
      }).catch((error) => {
        this.$u.hideLoading();
        this.$u.toast(error);
      })
    },
    initDoc2(){
      this.$u.loading("加载中...");
      const docParams = {id: this.docIns.docInsUuid, docUuid: this.docIns.docUuid, bizUuid: this.docIns.bizUuid,};
      certificateService.applyInfo(this.docIns.bizUuid).then((res) => {
        this.applyType = res.bean.applyType;
        this.$u.hideLoading();
        this.fieldData = res.bean;
      },(err) => {
        this.$u.hideLoading();
        this.$u.toast(err);
      });
    },
    initDoc(){
      this.$u.loading("加载中...");
	  
      const docParams = {id: this.docIns.docInsUuid, docUuid: this.docIns.docUuid, bizUuid: this.docIns.bizUuid,};
      Promise.all([
        certificateService.applyInfo(this.docIns.bizUuid),
        certificateService.getFieldAuditDoc(docParams),
        certificateService.goFiles(this.docIns.bizUuid, this.$FILE_GROUP_TYPE.l_audit_addr_img),// 经营地址照片
        certificateService.goFiles(this.docIns.bizUuid, this.$FILE_GROUP_TYPE.l_audit_place_img),// 经营场所图片
        certificateService.goFiles(this.docIns.bizUuid, this.$FILE_GROUP_TYPE.l_audit_other_img),// 其他图片
		    certificateService.goFiles(this.docIns.bizUuid, this.$FILE_GROUP_TYPE.l_audit_check_person_img),// 广西-被核查人签名
		    certificateService.goFiles(this.docIns.bizUuid, this.$FILE_GROUP_TYPE.l_audit_interested_person_img),// 广西-利害关系人签名
      ]).then((res) => {
        this.applyType = res[0].bean.applyType;
        this.$u.hideLoading();
        certificateService.getMainInfoById({  // 获取删改文书操作的状态
          handleMainUuid: this.docIns.bizUuid,
          applyType: this.applyType,
        }).then(rx => {
          if(rx.success){
            this.isLicDecide = rx.bean.isLicDecide;
            this.docUpdateStatus = rx.bean.docUpdateStatus;
            this.isElectronicCigarette = rx.bean.isElectronicCigarette;
          }else{
            console.log(rx.msg);
          }
        });
        let docDataArr = [];
        let str = '';
        [
          this.fieldData,
          docDataArr,
          this.$refs.confirmForm.addrImgs,
          this.$refs.confirmForm.placeImgs,
          this.$refs.confirmForm.otherImgs,
		      this.$refs.confirmForm.checkSignImgs,
		      this.$refs.confirmForm.interestedSignImgs,
        ] = [res[0].bean,res[1].data,res[2].data,res[3].data,res[4].data,res[5].data,res[6].data];
        let otp = {};
        this.objMerge(otp, this.fieldData);
        this.objMerge(otp, docDataArr[0]);
        // 群体类型
        if(otp.specialGroupType && otp.specialGroupType.indexOf('08') != -1){
          otp.isSpecialGroupTypeOther = true;
        }
        // 场地权属
        otp.tenancyBeginDate = this.getFormatDate(otp.tenancyBeginDate);
        otp.tenancyEndDate = this.getFormatDate(otp.tenancyEndDate);
        if(otp.groundOwnershipType == '02' || otp.groundOwnershipType == '03'){
          if((otp.isLongTenancy == true || otp.isLongTenancy == 'true') && otp.tenancyBeginDate != ''){
            otp.tenancyDate = otp.tenancyBeginDate + '至' + otp.tenancyEndDate;
          }else{
            otp.tenancyDate = "";
          }
        }else{
          otp.tenancyDate = "";
        }
        // 是否重大许项
        otp.isImportLic = otp.isImportLic && otp.isImportLic == 1 ? true : false;
        this.IMPORT_LIC_DATA.forEach((item) => {
          if(item.id == otp.isImportLicContent){
            str = item.name;
          }
        })
        otp.isImportLicName = str;
        if(this.step == 'assigntask'){
          this.docData = Object.assign(this.fieldData,otp);
          this.docData.businessAddrStreet2 = this.fieldData.businessAddrStreet;
          this.docData.groundOwnershipType2 = this.fieldData.groundOwnershipTypeName;
          this.docData.specialGroupTypeOther2 = this.fieldData.specialGroupTypeName;
          if((this.docData.applyType == M_APPLY_TYPE_CODE.ALTER || this.docData.applyType == M_APPLY_TYPE_CODE.CONTINUE)
            && (this.docData.isChangeBusinessAddr || this.docData.isChangeBusinessAddrObjective)
          ){
            this.docData.businessAddrStreet2 = this.fieldData.newBusinessAddrStreet;
            if(this.$u.test.isEmpty(docDataArr[0].businessAddrStreet)){
              this.docData.businessAddrAdc = this.fieldData.newBusinessAddrAdc;
              this.docData.businessAddrStreet = this.fieldData.newBusinessAddrStreet;
            }
          }
        } else {
          this.docData = otp;
          this.docData.businessAddrStreet2 = this.fieldData.businessAddrStreet;
          this.docData.groundOwnershipType2 = this.fieldData.groundOwnershipTypeName;
          this.docData.specialGroupTypeOther2 = this.fieldData.specialGroupTypeName;
          if((this.docData.applyType == M_APPLY_TYPE_CODE.ALTER || this.docData.applyType == M_APPLY_TYPE_CODE.CONTINUE)
		&& (this.docData.isChangeBusinessAddr || this.docData.isChangeBusinessAddrObjective)
          ){
            this.docData.businessAddrStreet2 = this.fieldData.newBusinessAddrStreet;
            if(this.$u.test.isEmpty(docDataArr[0].businessAddrStreet)){
              this.docData.businessAddrAdc = this.fieldData.newBusinessAddrAdc;
              this.docData.businessAddrStreet = this.fieldData.newBusinessAddrStreet;
            }
          }
        }
        if (!this.$u.test.isEmpty(this.docData.signNameFileId)) {
          this.docData.signImgList = [{
            gfiId: this.docData.signNameFileId,
          },];
        }
        let adcs = this.docData && this.docData.businessAddrAdc ? this.docData.businessAddrAdc.split(",") : [];
        if(adcs.length != 0 && !this.$u.test.isEmpty(this.docData.townCode)){ //
          this.getStreetsData(adcs[adcs.length - 1], this.docData.townCode);
        }else{
          this.docData.town = "";
          this.docData.village = "";
        }
        this.$refs.confirmForm.initAreaCitys(this.docData);
        this.handleConfirmData();
      },(err) => {
        this.$u.hideLoading();
        this.$u.toast(err);
      });
	  
	  
    },
    getFormatDate(str){
      if(this.$u.test.isEmpty(str)){
        return "";
      }
      let ob = "";
      try{
        let tm = (new Date(str)).getTime();
        if(isNaN(tm)){
          return str;
        }
        ob = this.$u.timeFormat(tm, 'yyyy-mm-dd');
        return ob;
      }catch(e){ console.log(e); }
      return "";
    },
    handleConfirmData(){
      let obj = {...this.docData,};
      if(obj.groundOwnershipType == '01'){
        obj.isLongTenancy = true;
        obj.tenancyBeginDate = "";
        obj.tenancyEndDate = "";
      }else{
        obj.isLongTenancy = obj.isLongTenancy == true ? true : false;
      }
      obj.groundOwnershipTypeName = this.$u.dic.getDicNameByKeyCode(this.$u.dic.DIC_KEYS.OWNERSHIP, obj.groundOwnershipType);
      obj.isNearSchool = obj.isNearSchool == true ? true : false;
      obj.isNearGarten = obj.isNearGarten == true ? true : false;
      obj.isSecurityProblems = obj.isSecurityProblems == true ? true : false;
   
      obj.isECigarPlace = obj.isECigarPlace == true || obj.isECigarPlace == 1 ? "1" : obj.isECigarPlace == false ? "0" : '';
      obj.isECigarScope = obj.isECigarScope == true || obj.isECigarScope == 1 ? "1" : obj.isECigarScope == false ? "0" : '';
      
      obj.isConvenientStore = obj.isConvenientStore == 1 ? true : false;
      obj.isSpecialClause = obj.isSpecialClause == 1 ? true : false;
      if (obj.isFixedPlace == undefined) {
        obj.isFixedPlace = true
      } else {
        obj.isFixedPlace = obj.isFixedPlace == true ? true : false;
      }
      if (obj.isAlone == undefined) {
        obj.isAlone = true
      } else {
        obj.isAlone = obj.isAlone == true ? true : false;
      }
      if(!obj.passiveCheckPersonName){
        obj.passiveCheckPersonName = obj.agentName ? obj.agentName : obj.managerName;
      }

      this.$refs.confirmForm.confirmInfo = obj;
      
      if(!this.$u.test.isEmpty(obj.managerPhotoPath)){
        this.$refs.confirmForm.managerPhoto = [{gfiId: obj.managerPhotoPath,},];
      }
      if(this.$refs.confirmForm.confirmInfo.fieldAuditDecide == true){
        this.$refs.confirmForm.fieldAuditVal = '1';
        if(this.$u.test.isEmpty(this.$refs.confirmForm.confirmInfo.fieldAuditDecideContent)){
          this.$refs.confirmForm.confirmInfo.fieldAuditDecideContent = "实地核查通过";
        }
      }else if(this.$refs.confirmForm.confirmInfo.fieldAuditDecide == false){
        this.$refs.confirmForm.fieldAuditVal = '0';
        if(this.$u.test.isEmpty(this.$refs.confirmForm.confirmInfo.fieldAuditDecideContent)){
          this.$refs.confirmForm.confirmInfo.fieldAuditDecideContent = "实地核查不通过";
        }
      }
      if(this.docData.longitude || this.docData.latitude){
        this.$set(this.$refs.confirmForm.confirmInfo,'gisXY','经度：' + this.docData.longitude + ", 纬度：" + this.docData.latitude);
      }
    },
    // 数据返回操作
    updateBackState(obj) {
      // 经营地址选择返回操作
      if(obj.pos){
        this.$set(this.$refs.confirmForm.confirmInfo,'gisXY','经度：' + obj.pos.longitude + ", 纬度：" + obj.pos.latitude);
        this.$set(this.$refs.confirmForm.confirmInfo,'longitude',obj.pos.longitude);
        this.$set(this.$refs.confirmForm.confirmInfo,'latitude',obj.pos.latitude);
		// 当前位置信息截图生成经营场所方位图 --上传图片  fsx 2024-2-23 开始
		if(obj.pos.isScreenshot && obj.pos.imgData) {
			this.$refs.confirmForm.uploadCutFile(obj.pos.imgData);
		}
		// 当前位置信息截图生成经营场所方位图 --上传图片  fsx 2024-2-23 结束
      }else if(obj.mapImg){
        this.$refs.confirmForm.uploadCutFile(obj.mapImg.imgSrc);
        this.$refs.confirmForm.setNearState(
          obj.mapImg.isNearSchool,
          obj.mapImg.nearSchoolDesc,
          obj.mapImg.isNearKindergarten,
          obj.mapImg.nearGartenDesc,
        );
      } else if(obj.thirdPartyDraw) {
		if(!!obj.thirdPartyDraw.base64) {
			console.log("11111111",obj)
			this.$refs.confirmForm.uploadAuditPlaceImg(obj.thirdPartyDraw.base64);
		}
	  }
    },
    // 查询街道数据
    getStreetsData(countryCode,streetCode){
      if(!countryCode){
        this.streetData = [];
        this.getVillages();
        return;
      }
      certificateService.getStreetsList({areaCode:countryCode,}).then(dr => {
        this.streetData = dr.data;
        this.$refs.confirmForm.streetData = this.handleSelcData(dr.data);
        // this.showDefalutVal(this.docData.townCode,this.streetData,true);
      });
      streetCode && this.getVillages(streetCode);
    },
    handleSelcData(data){
      let newStreetData = [];
      if(data.length > 0){
        data.forEach(item => {
          newStreetData.push({
            label:item.text,
            value:item.value,
          })
        });
      }
      return newStreetData;
    },
    // select默认显示数据
    showDefalutVal(val,list,flag){
      let indx = null;
      indx = list.findIndex(item => item.value == val);
      list.forEach((item) => {
        if(item.value == val){
          if(flag){
            this.$refs.confirmForm.confirmInfo.town = item.text || item.label;
            this.$refs.confirmForm.townDefaultVal = indx;
          }else{
            this.$refs.confirmForm.confirmInfo.village = item.text || item.label;
            this.$refs.confirmForm.villageDefaultVal = indx;
          }     
        } 
      });   
    },
    // 查询社区数据
    getVillages(streetCode){
      this.$refs.confirmForm.confirmInfo.townCode != this.docData.townCode && this.$refs.confirmForm.confirmInfo.village && this.$set(this.$refs.confirmForm.confirmInfo,'village','');

      if(!streetCode){
        this.villagesData = [];
        return;
      }
      this.$u.loading('正在查询中...');
      certificateService.getVillagesList({areaCode:streetCode,}).then(dr => {
        this.$u.hideLoading();
        this.villagesData = dr.data;
        this.$refs.confirmForm.villagesData = this.handleSelcData(dr.data);
        // this.showDefalutVal(this.docData.villageCode,this.villagesData,false);
      });
    },
    // 查询流程pdf文件
    searchApplyPdf(){
      let self = this;
      certificateService.getTimelineDocsByBizUuid({bizUuid:this.docIns.bizUuid,}).then((res) => {
        this.pdfFiles = res.data;
        // 查询当前文书是否已完成第三方签名
        this.pdfFiles.forEach(d => {
          this.searchIsSigned(d.docInsUuid).then(s => this.$set(this.docSign, d.docInsUuid, s));
        });
        setTimeout(() => {
          self.$refs['applyCt'].init();
        }, 500);
      }).catch((error) => {
        this.$u.toast(error);
      })
    },
    confirmBack(){
      let self = this;
      self.backPrev({
        paramKey: "queryInfo",
        param: this.queryForm,
      });
    },
    // 文书预览
    downloadFile(pdfFileId){
      if (!pdfFileId) {
        this.$u.toast("没有文书");
        return;
      }
      this.setRouteParam({fileId:pdfFileId,});
      this.$u.route('pages/commonPage/printerComponent');
    },
    // 提交、退出
    submitAudit(type){
      let [alertMsg,oldStreet,newStreet,] = ['',this.$u.trim(this.fieldData.businessAddrStreet || '','all'),this.$u.trim(this.$refs.confirmForm.confirmInfo.businessAddrStreet || '','all'),]
      if((this.docData.applyType == M_APPLY_TYPE_CODE.ALTER || this.docData.applyType == M_APPLY_TYPE_CODE.CONTINUE)
      && (this.docData.isChangeBusinessAddr || this.docData.isChangeBusinessAddrObjective)
      ){
        oldStreet = this.$u.trim(this.fieldData.newBusinessAddrStreet || '', 'all');
      }
      alertMsg = !newStreet.includes(oldStreet) ? '实地核查地址和申请表地址不一致,' : '';
      this.$modal.confirm(`${alertMsg}确定${type === "submit" ? '提交' : '退回'}吗？`, () => {
        this.$u.loading(`${type === "submit" ? '提交' : '退回'}中...`);
        let backInfo = this.$refs.confirmForm.confirmInfo;
        let self = this;
        for(let key in backInfo){
          this.docData[key] = backInfo[key];
        }
        // 为空没有选择的话，不给后端传值
        if(this.docData.isECigarPlace){
          this.docData.isECigarPlace = this.docData.isECigarPlace == '1' ? 1 : 0;
        }else{
          delete this.docData.isECigarPlace;  
        }
        if(this.docData.isECigarScope){
          this.docData.isECigarScope = this.docData.isECigarScope == '1' ? 1 : 0;
        }else{
          delete this.docData.isECigarScope;  
        }
        this.docData.isImportLic = this.docData.isImportLic == true ? '1' : '0';
        if(this.docData.isNearSchool == undefined){
          this.$set(this.docData,'isNearSchool',false)
        }
        if(this.docData.isNearGarten == undefined){
          this.$set(this.docData,'isNearGarten',false)
        }
        if(this.docData.isSecurityProblems == undefined){
          this.$set(this.docData,'isSecurityProblems',false)
        }
        if(this.docData.isFixedPlace == undefined){
          this.$set(this.docData,'isFixedPlace',false)
        }
        if(this.docData.isAlone == undefined){
          this.$set(this.docData,'isAlone',false)
        }
        this.docData.handleMainUuid = this.docIns.bizUuid;
        if(type == 'back'){
          console.log(666)
          if(this.docData.isConvenientStore == true){
            this.docData.isConvenientStore = 1;
          }else{
            this.docData.isConvenientStore = 0;
          }
          if(this.docData.isSpecialClause == true){
            this.docData.isSpecialClause = 1;
          }else{
            this.docData.isSpecialClause = 0;
          }
          certificateService.backFieldAuditDoc(this.docData, this.docIns.docUuid,
            this.docIns.configIns.titemUuid,this.docIns.docInsUuid,
            {
              gfaCode:this.step,
              approveInfo:'',
              approveDate:this.$u.timeFormat( Date.now(),'yyyy年mm月dd日'),
              approvePersonUuid:this.curUser.user.personUuid,
              isAgree:'',
              taskId:'',
            }
          ).then(res => {
            if(res.success){
              console.log(666)
              if(res.success){
                this.$u.toast("退回成功");
                this.saveBehaviorLog(LOG_OP_TYPE.agree, this.docIns);
                self.backPrev({
                  paramKey: "queryInfo",
                  param : {tabIndex:0,curIndex:this.preParams.curIndex,},
                });
              }else{
                this.$u.toast(res.msg);
              }
            }
          })
        }else if(type == 'submit'){
          if(this.docData.specialGroupType && this.docData.specialGroupType.indexOf('08') == -1){
            this.docData.specialGroupTypeOther = '';
          }
          if(this.docData.isConvenientStore == true){
            this.docData.isConvenientStore = 1;
          }else{
            this.docData.isConvenientStore = 0;
          }
          if(this.docData.isSpecialClause == true){
            this.docData.isSpecialClause = 1;
          }else{
            this.docData.isSpecialClause = 0;
          }
          certificateService.saveFieldAuditDoc(this.docData, this.docIns.docUuid,
            this.docIns.configIns.titemUuid,this.docIns.docInsUuid,
            {
              gfaCode:this.step,
              approveInfo:'实地核查结束',
              approveDate:this.$u.timeFormat( Date.now(),'yyyy年mm月dd日'),
              approvePersonUuid:this.curUser.user.personUuid,
              isAgree:1,
              taskId:'',
            }
          ).then(dr => {
            this.$u.hideLoading();
            if([M_APPLY_TYPE_CODE.ALTER, M_APPLY_TYPE_CODE.CONTINUE, M_APPLY_TYPE_CODE.RECOVER].includes(this.applyType) && this.step !== 'assigntaskCheck'){
              this.$modal.confirm("是否进行实地核查", () => {
                this.$u.loading("加载中");
                if (type === 'submit') {
                // 设为true则决定书提交后会自动从实地核查信息中提取许可证所用到的信息
                  dr.bean.isInspect = "true";
                  // let docInfo = dr.data[0].configIns;
                  // 提交参数
                  dr.beginTime = this.beginTime;
                  this.setRouteParam(dr);
                  this.$u.route('/pages/certificate/components/auditor')
                }
              }, () => {
                this.handleNoFieldAudit(dr)
              }, "是", "否");
            } else {
              if (type === 'submit') {
                if (this.step === 'assigntaskCheck') {
                  this.handleNoFieldAudit(dr)
                } else {
                  // 设为true则决定书提交后会自动从实地核查信息中提取许可证所用到的信息
                  dr.bean.isInspect = true;
                  dr.beginTime = this.beginTime;
                  this.setRouteParam(dr)
                  this.$u.route('/pages/certificate/components/auditor')
                }
              }
            }
          }).catch((err) => {
            this.$u.hideLoading();
            this.$u.toast(err.msg);
          });
        }
      });
    },
    async handleNoFieldAudit (dr) {
      if (this.step === 'assigntaskCheck') {
        delete dr.bean.isActive;
      } else {
        dr.bean.isInspect = "false";
        dr.bean.inspectType = "false";
      }
      dr.bean.currentStep = this.step;
      let docInfo = dr.data[0].configIns;
      // 提交参数
      let submitParams = {
        docUuid:docInfo.docUuid,
        docInsUuid:docInfo.docInsUuid || dr.data[0].docInsUuid,
        titemUuid:docInfo.titemUuid,
        gfaCode:this.step,
        approveInfo: "",
        nextPersons: "",
        approveDate: "",
        approvePersonUuid: this.curUser.user.personUuid,
        isAgree: this.step === 'assigntaskCheck' ? '1' : '',
        taskId:'',
      }
      this.$u.loading("提交中...");
      try {
        const doc = await certificateService.submitFieldAuditDoc(dr.bean, submitParams)
        this.$u.hideLoading();
        if(doc.success){
          this.$u.toast("提交成功");
          this.saveBehaviorLog(LOG_OP_TYPE.submitDoc, this.docIns);
          this.backPrev({
            paramKey: "queryInfo",
            param : {tabIndex:0,curIndex:this.preParams.curIndex,},
          });
        }else{
          this.$u.toast(doc.msg);
        }
      } catch (err) {
        this.$u.hideLoading();
        this.$u.toast(err.msg);
      }
    },
    saveAudit(type){
      if(type == 'submit'){
        let isValid = this.$refs.confirmForm.validForm();
        if(!isValid) return;
        if((!this.$refs.confirmForm.addrImgs || this.$refs.confirmForm.addrImgs.length == 0)){
          this.$u.toast('请上传经营地址图');
          return;
        }
      }
      let backInfo = this.$u.deepClone(this.$refs.confirmForm.confirmInfo);
      let self = this;
      let newDocData = this.$u.deepClone(this.docData);
      for(let key in backInfo){
        newDocData[key] = backInfo[key];
      }
      // 为空没有选择的话，不给后端传值
      if(newDocData.isECigarPlace){
        newDocData.isECigarPlace = newDocData.isECigarPlace == '1' ? 1 : 0;
      }else{
        delete newDocData.isECigarPlace;  
      }
      if(newDocData.isECigarScope){
        newDocData.isECigarScope = newDocData.isECigarScope == '1' ? 1 : 0;
      }else{
        delete newDocData.isECigarScope;  
      }
  
      newDocData.isImportLic = newDocData.isImportLic == true ? '1' : '0';
      if(this.applyType != M_APPLY_TYPE_CODE.CONTINUE && newDocData.isImportLic == '1' && this.$u.test.isEmpty(newDocData.isImportLicContent) && type == "submit"){
        this.$u.toast('请选择重大许可项');
        return;
      }
      if(newDocData.fieldAuditDecide == undefined && type == "submit"){
        this.$u.toast('请选择实地核查意见');
        return;
      }
      let [alertMsg,oldStreet,newStreet,] = ['',this.$u.trim(this.fieldData.businessAddrStreet || '','all'),this.$u.trim(this.$refs.confirmForm.confirmInfo.businessAddrStreet || '','all'),]
      if((this.docData.applyType == M_APPLY_TYPE_CODE.ALTER || this.docData.applyType == M_APPLY_TYPE_CODE.CONTINUE)
      && (this.docData.isChangeBusinessAddr || this.docData.isChangeBusinessAddrObjective)
      ){
        oldStreet = this.$u.trim(this.fieldData.newBusinessAddrStreet || '', 'all');
      }
      alertMsg = !newStreet.includes(oldStreet) ? '实地核查地址和申请表地址不一致,' : '';
      this.$modal.confirm(`${alertMsg}确定${type == "submit" ? '提交' : '保存'}吗？`, async () => {
        this.$u.loading("保存中");
        if(newDocData.isNearSchool == undefined){
          this.$set(newDocData,'isNearSchool',false)
        }
        if(newDocData.isNearGarten == undefined){
          this.$set(newDocData,'isNearGarten',false)
        }
        if(newDocData.isSecurityProblems == undefined){
          this.$set(newDocData,'isSecurityProblems',false)
        }
        if(newDocData.isFixedPlace == undefined){
          this.$set(newDocData,'isFixedPlace',false)
        }
        if(newDocData.isAlone == undefined){
          this.$set(newDocData,'isAlone',false)
        }
        if(newDocData.isConvenientStore == true){
          newDocData.isConvenientStore = 1;
        }else{
          newDocData.isConvenientStore = 0;
        }
        // 是否勾选放宽情形
        if(newDocData.isSpecialClause == true){
          newDocData.isSpecialClause = 1;
        }else{
          newDocData.isSpecialClause = 0;
        }

        newDocData.handleMainUuid = this.docIns.bizUuid;
        console.log('提交的参数：' + JSON.stringify(newDocData))
        if(newDocData.specialGroupType && newDocData.specialGroupType.indexOf('08') == -1){
          newDocData.specialGroupTypeOther = '';
        }
        try {
          const dr = await certificateService.saveFieldAuditDoc(newDocData, this.docIns.docUuid,
            this.docIns.configIns.titemUuid,this.docIns.docInsUuid,
            {
              gfaCode:this.step,
              approveInfo:'实地核查结束',
              approveDate:this.$u.timeFormat( Date.now(),'yyyy年mm月dd日'),
              approvePersonUuid:this.curUser.user.personUuid,
              isAgree:1,
              taskId:'',
            }
          )
          this.$u.hideLoading();
          if (type === 'submit') {
            // 设为true则决定书提交后会自动从实地核查信息中提取许可证所用到的信息
            dr.bean.isInspect = "true";
            // 判断当前是否为流程最后会签人， 若是则弹出选择复核人
            const isLastUser = await this.getIsLastUser()
            if (isLastUser) {
              dr.stepType = 'recheck';
              this.setRouteParam(dr);
              this.$u.route('/pages/certificate/components/auditor');
              return;
            }
            let docInfo = dr.data[0].configIns;
            // 提交参数
            let submitParams = {
              docUuid:docInfo.docUuid,
              docInsUuid:docInfo.docInsUuid,
              titemUuid:docInfo.titemUuid,
              gfaCode:this.step,
              approveInfo:'实地核查结束',
              approveDate:this.$u.timeFormat( Date.now(),'yyyy年mm月dd日'),
              approvePersonUuid:this.curUser.user.personUuid,
              isAgree:1,
              taskId:'',
            }
            this.$u.loading("提交中...");
            certificateService.submitFieldAuditDoc(dr.bean, submitParams, !isLastUser).then((doc) => {
              this.$u.hideLoading();
              if(doc.success){
                this.$u.toast("提交成功");
                this.saveBehaviorLog(LOG_OP_TYPE.submitDoc, this.docIns);
                self.backPrev({
                  paramKey: "queryInfo",
                  param : {tabIndex:0,curIndex:this.preParams.curIndex,},
                });
              }else{
                this.$u.toast(doc.msg);
              }
            }).catch((err) => {
              this.$u.hideLoading();
              this.$u.toast(err.msg);
            });
          }else{
            this.$u.toast('保存成功');
            this.saveBehaviorLog(LOG_OP_TYPE.saveDoc, this.docIns);
          }
        } catch (err) {
          this.$u.hideLoading();
          this.$u.toast(err.msg);
        };
      });
    },
    /**
	 * @param {Boolean} status 提交还是保存
	 */
    saveBehaviorLog(status, doc){
      commonService.getCurrentTime().then(res2 => {
        let param = {
          bizUuid: doc.bizUuid,
          docUuid:doc.docUuid,
          docInsUuid: doc.docInsUuid,
          bizType:LOG_STATUS.B008,
          operationType: status,
          beginTime: this.beginTime,
          endTime: res2.success ? res2.msg : this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss'),
          remark: doc.configIns.docName,
        };
        this.beginTime = param.endTime;
        commonService.saveBehaviorLog(param).then(res => {
          console.log(res);
        }).catch(e => {
          console.log(e);
        });
      });
    },
    // 查询是否已完成第三方签名
    searchIsSigned(listDocInsUuid) {
      return commonService.isSigned(listDocInsUuid).then(s => {
        return s.success;
      });
    },
    // 第三方签名
    handleSign(signDocInsUuid) {
      this.$u.loading("检查签名中...");
      commonService.isSigned(signDocInsUuid).then(s => {
        this.$u.hideLoading();
        if (!s.success) {
          // 再次查询时重置一下结果，改变图标显示
          this.$set(this.docSign, signDocInsUuid, s.success)
          this.$u.toast(s.msg);
          return;
        }

        let {managerName, managerIdCardNo,} = this.fieldData;
        if (!managerName || !managerIdCardNo) {
          this.$u.hideLoading();
          this.$u.error(!managerName ? "缺少被核查人姓名" : "缺少被核查人身份证号");
          return;
        }
        // 检查当事人数据是否正确，再调用接口
        commonService.dsrSign(signDocInsUuid, managerName, managerIdCardNo).then(dr => {
          this.$u.hideLoading();
          if (!dr.success) {
            this.$u.error(dr.msg);
            return;
          }
          let qrcodeUrl = `${this.signViewUrl}?token=${dr.bean}`;
          // #ifdef H5-WECHAT
          this.$modal.confirm("是否生成二维码给当事人扫码签名？", () => {
            QRCode.toDataURL(qrcodeUrl).then(path => {
              this.qrcodeImg = path;
              this.qrcodeShow = true;
            }).catch(err => {
              this.$u.error(err);
            });
          }, "生成二维码");
          // #endif
          // #ifndef H5-WECHAT
          this.$modal.confirm("是否生成二维码给当事人扫码签名？", () => {
            QRCode.toDataURL(qrcodeUrl).then(path => {
              this.qrcodeImg = path;
              this.qrcodeShow = true;
            }).catch(err => {
              this.$u.error(err);
            });
          }, () => {
            this.$modal.openNewTab(qrcodeUrl);
          }, "生成二维码", "本机签名");
          // #endif
        });
      });
    },
    // 查询当前是否为流程最后审批人
    async getIsLastUser() {
      var res = await certificateService.isLastUser({
        bizUuid: this.docIns.docInsUuid,
        docCode: 'lic-item-02-01-01'
      });
      if (res.success) {
        return res.bean;
      } else {
        this.$u.toast("提交失败!");
      }
    }
  },
};
</script>

<style lang="scss" scoped>
@import "style/certificate/common.scss";
.page{
  padding: 0;
}
.qrcodeContainer {
  text-align: center;
  img {
    width: 95%;
  }
  p {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
}
</style>
